using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 再生Buff - 持续恢复生命值
/// </summary>
public class RegenerationBuff : BuffBase
{
    private float m_TickInterval = 1.0f; // 每秒恢复一次
    private float m_LastTickTime;
    private long m_HealPerTick;
    private float m_HealMultiplier = 1.0f; // 治疗倍率

    public RegenerationBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
        if (buffData is RegenerationData regenData)
        {
            m_HealPerTick = regenData.HealPerTick;
            m_TickInterval = regenData.TickInterval;
            m_HealMultiplier = regenData.HealMultiplier;
        }
    }

    protected override void OnStart()
    {
        base.OnStart();
        m_LastTickTime = 0f;
        
        // 播放再生特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        Logger.Log("RegenerationBuff", $"{Target.name} 开始再生，每秒恢复 {m_HealPerTick} 点生命值");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        
        // 检查是否到了恢复生命值的时间
        if (Time.time - m_LastTickTime >= m_TickInterval)
        {
            ApplyRegeneration();
            m_LastTickTime = Time.time;
        }
    }

    private void ApplyRegeneration()
    {
        if (Target != null && !Target.HealthComponent.IsDead)
        {
            // 计算实际治疗量（考虑倍率）
            long actualHeal = (long)(m_HealPerTick * m_HealMultiplier);
            
            // 恢复生命值
            Target.HealthComponent.TakeHeal(actualHeal);
            
            Logger.Log("RegenerationBuff", $"{Target.name} 恢复生命值 {actualHeal}");
            
            // 触发治疗事件
            var args = ReferencePool.Acquire<EntityHealEventArgs>();
            args.Entity = Target;
            args.HealAmount = actualHeal;
            EventHelper.Fire(this, args);
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log("RegenerationBuff", $"{Target.name} 再生效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Regeneration"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return true; // 再生效果可以叠加，刷新持续时间
    }
}